package com.xhwl.logistics.component;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.xhwl.logistics.dto.http.query.QueryCommonCheAnDTO;
import com.xhwl.logistics.util.AboutDateUtil;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Component
public class SignForCheAn {

    public QueryCommonCheAnDTO<?> sign(QueryCommonCheAnDTO<?> queryCommonCheAnDTO, String privateKey) {
        queryCommonCheAnDTO.setFrom("UT");
        queryCommonCheAnDTO.setTimestamp(AboutDateUtil.dateToString(new Date()));
        queryCommonCheAnDTO.setNonce(String.valueOf(RandomUtil.randomInt(1, 100)));

        List<String> stringList = new ArrayList<>(Arrays.asList(queryCommonCheAnDTO.getFrom(), queryCommonCheAnDTO.getTimestamp(), queryCommonCheAnDTO.getNonce()));
        Collections.sort(stringList);
        Optional.ofNullable(queryCommonCheAnDTO.getData()).ifPresent(data -> stringList.add(JSON.toJSONString(data)));

        queryCommonCheAnDTO.setSign(SecureUtil.hmacSha1(privateKey).digestBase64(String.join("", stringList), false));
        return queryCommonCheAnDTO;
    }

}
